package com.alon.spring01.study.threadLocal;

/**
 * @program: spring01
 * @description: 测试ThreadLocal,达到线程隔离机制，确保线程安全
 * @author: yulongguang
 * @create: 2019-07-16 22:19
 **/
public class SeqCount {

    /**
     * 返回基本类型
     */
    private static ThreadLocal<Integer> seqCount = new ThreadLocal<Integer>() {
        @Override
        public Integer initialValue() {
            return 0;
        }
    };

    public int nextSeq() {
        seqCount.set(seqCount.get() + 1);
        return seqCount.get();
    }

    private static class SeqThread extends Thread {
        private SeqCount seqCount;

        SeqThread(SeqCount seqCount) {
            this.seqCount = seqCount;
        }

        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName() + "seqCount:" + seqCount.nextSeq());
            }
        }
    }

    public static void main(String[] args) {
        SeqCount seqCount = new SeqCount();
        SeqThread seqThread1 = new SeqThread(seqCount);
        SeqThread seqThread2 = new SeqThread(seqCount);
        SeqThread seqThread3 = new SeqThread(seqCount);
        SeqThread seqThread4 = new SeqThread(seqCount);
        seqThread1.start();
        seqThread2.start();
        seqThread3.start();
        seqThread4.start();

    }
}
